//app.js
const {
  postUserInfo,
  imageBaseUrl,
  collectionListByType
} = require('api/url.js')
const cityData = require('./utils/cityData')
App({
  /**
   * @method
   * @desc 请求用户数收藏
   * @param page,size,fUserId
   */
  loadCollections(page, size, loginName) {
    let that = this
    wx.request({
      url: collectionListByType,
      data: {
        page,
        size,
        loginName,
        token: wx.getStorageSync('token')
      },
      success(res) {
        if (res.data.code === 0) {
          if (res.data.response.cont.products && res.data.response.cont.products.length > 0) { //如果有收藏保存id
            that.globalData.collections = res.data.response.cont.products.map(val => val.fId)
          } else { //如果没有为空
            that.globalData.collections = []
          }
        } else {
          wx.showToast({
            title: '获取收藏失败',
            icon: 'none'
          })
        }
      },
      fail() {
        wx.showToast({
          title: '获取收藏接口错误',
          icon: 'none'
        })
      }
    })
  },
  /**
   * 微信登录获取usercode
   * return {code,errMsg}
   */
  getUserCode() {
    let that = this
    return new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          if (res.errMsg === 'login:ok') {
            that.globalData.userCode = res.code
            resolve(res)
          } else {
            wx.showToast({
              title: '微信登录失败',
              icon: 'none'
            })
            reject(res)
          }
        }
      })
    })
  },
  /**
   * @method
   * @desc 获取用户微信登录信息
   * @resolve true:有授权 false:没有授权
   */
  getWxUserInfo() {
    let that = this
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: res => {
                that.globalData.wxUserInfo = res.userInfo
                resolve(true)
              }
            })
          } else {
            resolve(false)
          }
        }
      })
    })
  },
  /**
   * @method
   * @desc 获取用户自定义信息
   * @resolve true:获取了用户信息 false:未获取到用户自定义信息
   */
  getUserInfo() {
    let that = this
    return new Promise((resolve, reject) => {
      wx.request({
        url: postUserInfo,
        method: 'GET',
        data: {
          jsCode: that.globalData.userCode,
          nickName: that.globalData.wxUserInfo.nickName,
          gender: that.globalData.wxUserInfo.gender,
          avatarUrl: that.globalData.wxUserInfo.avatarUrl,
          province: that.globalData.wxUserInfo.province,
          city: that.globalData.wxUserInfo.city,
          country: that.globalData.wxUserInfo.country,
        },
        success(res) {
          if (res.data.code == 0) {
            wx.setStorageSync('token', res.data.response.extra)
            that.globalData.userInfo = res.data.response.cont
            if (that.globalData.collections.length <= 0) {
              that.loadCollections(0, 9999, that.globalData.userInfo.loginname)
            }
            resolve(res)
          } else {
            resolve(res)
          }
        },
        fail(res) {
          resolve(res)
        }
      })
    })

  },
  /**
   * @method
   * @desc 用户登录
   * @resolve success:成功 fail:失败 noAuthorize:未授权
   */
  userLogin() {
    let that = this
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '用户登录',
        mask: true
      })
      if (that.globalData.userInfo) { //如果已经有自定义用户信息
        resolve('success')
      } else if (that.globalData.wxUserInfo) { //如果已经有微信登录用户信息
        //登录用户获取自定义信息
        that.getUserInfo().then(res2 => {
          if (res2.data.code === 0) {
            resolve('success')
          } else {
            resolve('fail')
          }
        })
      } else if (that.globalData.userCode) { //如果已经有用户码
        that.getWxUserInfo().then(res1 => {
          if (res1) { //有授权
            //获取用户自定义信息
            that.getUserInfo().then(res2 => {
              if (res2.data.code === 0) {
                resolve('success')
              } else {
                resolve('fail')
              }
            })
          } else { //没有授权
            resolve('noAuthorize')
          }
        })
        //获取自定义用户信息
      } else {
        that.getUserCode().then(res => {
          that.getWxUserInfo().then(res1 => {
            if (res1) { //有授权
              //获取用户自定义信息
              that.getUserInfo().then(res2 => {
                if (res2.data.code === 0) {
                  resolve('success')
                } else {
                  resolve('fail')
                }
              })
            } else { //没有授权
              resolve('noAuthorize')
            }
          })
        })
      }
    })
  },

  addrToCode(addrs) {
    if (addrs[0] === addrs[1] || addrs[1] === '县') {
      addrs = [addrs[0], addrs[2]]
    }
    let currentList = cityData
    let addrItem
    const codeData = {}
    if (addrs[0] && (addrItem = currentList.find(i => i.name === addrs[0]))) {
      codeData.province = addrItem.name
      codeData.provinceNum = addrItem.id
      currentList = addrItem.sub
    } else {
      throw new Error(`no match province for ${addrs[0]}`)
    }
    if (addrs[1] && (addrItem = currentList.find(i => i.name === addrs[1]))) {
      codeData.city = addrItem.name
      codeData.cityNum = addrItem.id
      currentList = addrItem.sub
    } else {
      throw new Error(`no match city for ${addrs[1]}`)
    }
    if (addrs[2] && (addrItem = currentList.find(i => i.name === addrs[2]))) {
      codeData.area = addrItem.name
      codeData.areaNum = addrItem.id
    }
    return codeData
  },
  onLaunch: function() {
    let that = this
    that.globalData.imageBaseUrl = imageBaseUrl
    //获取系统信息
    that.globalData.systemInfo = wx.getSystemInfoSync()
    that.globalData.isIPX = that.globalData.systemInfo.model.indexOf('iPhone X')===-1?false:true
    that.getUserCode()
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    //扩充监听事件数量
  },
  globalData: {
    userInfo: null, //自定义登录信息
    wxUserInfo: null, //微信登录用户信息
    systemInfo: null, //系统信息
    userCode: null, //用户码
    imageBaseUrl: null, //图片基础地址
    collections: [], //用户收藏数据
    isIPX:false,//是否是iPhone x
  }
})